import 'package:flutter/material.dart';
import 'package:myturngame/Theme.dart';
import 'package:myturngame/bean/combat/reward.dart';
import 'package:myturngame/bean/game_map.dart';
import 'package:myturngame/bean/message.dart';
import 'package:myturngame/bean/role_in_map.dart';
import 'package:myturngame/colors.dart';
import 'package:myturngame/facotry/enemy_factory.dart';
import 'package:myturngame/state/SelectSkillChangeNotifier.dart';
import 'package:myturngame/widget/home/layout_combat.dart';
import 'package:myturngame/widget/home/layout_home_operation.dart';
import 'package:myturngame/widget/message_window.dart';
import 'package:myturngame/widget/text_decoration.dart';
import 'package:provider/provider.dart';

import 'common/game_global.dart';

void main() {
  GameGlobal.init().then((value) => runApp(const MyApp()));
}

GlobalKey gameLayoutKey = GlobalKey();

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (_) => SelectSkillChangeNotifier())
      ],
      child: Consumer<SelectSkillChangeNotifier>(
        builder: (BuildContext context, selectSkill, child) {
          return MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(
                // This is the theme of your application.
                //
                // Try running your application with "flutter run". You'll see the
                // application has a blue toolbar. Then, without quitting the app, try
                // changing the primarySwatch below to Colors.green and then invoke
                // "hot reload" (press "r" in the console where you ran "flutter run",
                // or simply save your changes to "hot reload" in a Flutter IDE).
                // Notice that the counter didn't reset back to zero; the application
                // is not restarted.
                primarySwatch: Colors.blue,
                backgroundColor: Colors.white),
            home: GameLayout(key: gameLayoutKey),
          );
        },
      ),
    );

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          // This is the theme of your application.
          //
          // Try running your application with "flutter run". You'll see the
          // application has a blue toolbar. Then, without quitting the app, try
          // changing the primarySwatch below to Colors.green and then invoke
          // "hot reload" (press "r" in the console where you ran "flutter run",
          // or simply save your changes to "hot reload" in a Flutter IDE).
          // Notice that the counter didn't reset back to zero; the application
          // is not restarted.
          primarySwatch: Colors.blue,
          backgroundColor: Colors.white),
      home: GameLayout(key: gameLayoutKey),
    );
  }
}

///游戏界面
class GameLayout extends StatefulWidget {
  const GameLayout({Key? key}) : super(key: key);

  @override
  State<GameLayout> createState() => _GameLayoutState();
}

class _GameLayoutState extends State<GameLayout> {
  String currentMap = GameMap.map002;

  List<Message> messageList = <Message>[];

  RoleInMap? mapRoleToCombat;

  @override
  void initState() {
    super.initState();
    //初始化玩家信息
    initPlayer();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> children = [
      const Align(alignment: Alignment.topRight, child: UserAndPet()),
      Align(
          alignment: Alignment.bottomCenter,
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Align(
                alignment: Alignment.bottomLeft,
                //系统消息栏
                child: MessageWindow(messageList),
              ),
              const Spacer(),
              LayoutOperation((String map) {
                //地图点击事件
                setState(() {
                  currentMap = map;
                });
              }, (Message message) {
                //添加系统消息
                setState(() {
                  messageList.add(message);
                });
              })
            ],
          )),
      //左上角地图
      Align(
          alignment: Alignment.topLeft,
          child: Container(
            width: 70,
            height: 70,
            decoration: BoxDecoration(
                border: Border.all(), borderRadius: BorderRadius.circular(35)),
            alignment: Alignment.center,
            child: Text(currentMap, style: textStyle3),
          )),
    ];
    if (mapRoleToCombat != null) {
      //战斗界面
      children.add(Align(
        alignment: Alignment.center,
        child: CombatLayout(mapRoleToCombat!, (Reward? reward) {
          setState(() {
            mapRoleToCombat = null;
            //结算战利品
            if (reward != null) {
              _dealReward(reward);
            }
            GameGlobal.player.recoverHp();
            GameGlobal.player.pet?.recoverHp();
          });
        }),
      ));
    } else {
      //怪物和NPC列表
      if (currentMap.hasDarkEnemy()) {
        children.add(Align(
          alignment: Alignment.center,
          child: GestureDetector(
            onTap: () {
              setState(() {
                mapRoleToCombat = createMapEnemy(currentMap);
              });
            },
            child: BorderContainer(
              Text(
                "Lv${currentMap.level()} 巡逻",
                style: textStyle,
              ),
            ),
          ),
        ));
      }
    }
    // children.add(SlideTransitionPage());

    return Container(
      decoration: const BoxDecoration(color: Colors.white),
      padding: const EdgeInsets.only(top: 20, bottom: 20),
      child: Stack(
        children: children,
      ),
    );
  }

  ///初始化玩家
  void initPlayer() {
    //增加一只宠物
    // GameGlobal.player.pet = createMonster("大海龟");
    debugPrint("initPlayer");
  }

  ///处理战利品
  void _dealReward(Reward reward) {
    for (var element in reward.bagObject) {
      GameGlobal.player.bag.putIn(element);
      messageList.add(Message.text("获得 ${element.name}"));
    }
    if (reward.exp != 0) {
      GameGlobal.player.exp += reward.exp;
      messageList.add(Message.text("获得 ${reward.exp} 经验"));
    }
    if (reward.money != 0) {
      GameGlobal.player.money += reward.money;
      messageList.add(Message.text("获得 ${reward.money} 金钱"));
    }
  }
}

///玩家和宠物
class UserAndPet extends StatelessWidget {
  const UserAndPet({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          //宠物
          SizedBox(
            width: 40,
            height: 40,
            child: OutlinedButton(onPressed: () {}, child: const Text("宠")),
          ),
          const RoleProgress(),
          const SizedBox(width: 5),
          //人物
          SizedBox(
            width: 40,
            height: 40,
            child: OutlinedButton(onPressed: () {}, child: const Text("我")),
          ),
          const RoleProgress(),
        ],
      ),
    );
  }
}

///角色进度条
class RoleProgress extends StatelessWidget {
  const RoleProgress({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 60,
      height: 40,
      child: Column(
        children: [
          SizedBox(
            height: 13,
            child: LinearProgressIndicator(value: 1, color: hpColor),
          ),
          SizedBox(
            height: 13,
            child: LinearProgressIndicator(value: 1, color: mpColor),
          ),
          SizedBox(
            height: 13,
            child: LinearProgressIndicator(value: 1, color: expColor),
          )
        ],
      ),
    );
  }
}
